package util;


import java.sql.*;

public class JdbcUtils {
    private static final String USER = "root";//用户名
    private static final String PASSWORD = "123456";//密码
    private static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    public static Connection getConnection() {
        try {
            Class.forName(DRIVER);
            //jdk1.6及其以上,mysql-connector-java-5.1.5.jar版本以上。可以不用显性注册驱动，会自动完成。
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (Exception e) {
            //若数据库连接失败，抛出运行时异常
            throw new RuntimeException(e);
        }
    }

    //当操作完一次数据库后，都要及时的将连接关闭，以防内存泄漏
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            //若数据库操作失败，抛出运行时异常
            throw new RuntimeException(e);
        }
    }
}